<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 实时聊天</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: #333;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            display: flex;
            flex-direction: column;
            width: 100%;
            max-width: 1000px;
            height: 90vh;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }

        header {
            background: #2c3e50;
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }

        h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }

        .subtitle {
            font-size: 16px;
            opacity: 0.8;
        }

        .online-count {
            position: absolute;
            right: 20px;
            top: 20px;
            background: #3498db;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 14px;
        }

        .content {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .sidebar {
            width: 250px;
            background: #34495e;
            color: white;
            padding: 20px;
            overflow-y: auto;
            border-right: 1px solid #2c3e50;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 20px;
        }

        .status {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            padding: 10px 15px;
            border-radius: 10px;
            background: #f8f9fa;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .connected {
            background: #2ecc71;
        }

        .disconnected {
            background: #e74c3c;
        }

        .connecting {
            background: #f39c12;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            border: 1px solid #ddd;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        }

        .messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f9f9f9;
        }

        .message {
            margin-bottom: 15px;
            padding: 12px 15px;
            border-radius: 10px;
            max-width: 80%;
            word-wrap: break-word;
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .received {
            background: #e3f2fd;
            align-self: flex-start;
            border-top-left-radius: 0;
        }

        .sent {
            background: #c8e6c9;
            align-self: flex-end;
            margin-left: auto;
            border-top-right-radius: 0;
        }

        .system {
            background: #fff3e0;
            text-align: center;
            max-width: 100%;
            font-style: italic;
            margin: 10px auto;
        }

        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }

        .message-avatar {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 8px;
            color: white;
            font-weight: bold;
            font-size: 12px;
        }

        .message-info {
            font-size: 12px;
            color: #666;
        }

        .input-area {
            display: flex;
            padding: 15px;
            background: white;
            border-top: 1px solid #ddd;
        }

        input, textarea, button {
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }

        .message-input {
            flex: 1;
            margin-right: 10px;
            resize: none;
            height: 60px;
        }

        .send-btn {
            background: #3498db;
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }

        .send-btn:hover:not(:disabled) {
            background: #2980b9;
        }

        .send-btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
        }

        .user-list {
            list-style: none;
        }

        .user-item {
            padding: 10px 15px;
            margin-bottom: 10px;
            background: rgba(255,255,255,0.1);
            border-radius: 8px;
            display: flex;
            align-items: center;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 10px;
            color: white;
            font-weight: bold;
        }

        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .control-btn {
            padding: 10px 15px;
            background: #34495e;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .control-btn:hover:not(:disabled) {
            background: #2c3e50;
        }

        .control-btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
        }

        .connection-info {
            margin-top: 20px;
            padding: 15px;
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
            font-size: 14px;
        }

        .connection-info h3 {
            margin-bottom: 10px;
            color: #ecf0f1;
        }

        .code-block {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            font-family: monospace;
            font-size: 12px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>WebSocket 实时聊天</h1>
        <div class="subtitle">真实的多窗口通信演示</div>
        <div class="online-count">在线: <span id="onlineCount">0</span></div>
    </header>

    <div class="content">
        <div class="sidebar">
            <h3>在线用户</h3>
            <ul class="user-list" id="userList">
                <!-- 用户列表将通过JavaScript动态添加 -->
            </ul>

            <div class="connection-info">
                <h3>连接信息</h3>
                <p>服务器: <span id="serverUrl">未连接</span></p>
                <p>用户ID: <span id="userId">-</span></p>

                <div class="code-block">
                    // WebSocket连接示例
                    const socket = new WebSocket('ws://localhost:8080');

                    socket.onmessage = (event) => {
                    const data = JSON.parse(event.data);
                    // 处理服务器消息
                    };
                </div>
            </div>
        </div>

        <div class="main">
            <div class="status">
                <div class="status-indicator disconnected" id="statusIndicator"></div>
                <span id="statusText">WebSocket 连接状态: 未连接</span>
            </div>

            <div class="controls">
                <button class="control-btn" id="connectBtn">连接服务器</button>
                <button class="control-btn" id="disconnectBtn" disabled>断开连接</button>
                <button class="control-btn" id="clearBtn">清空消息</button>
            </div>

            <div class="chat-container">
                <div class="messages" id="messages">
                    <div class="message system">
                        <div class="message-info">系统消息</div>
                        欢迎使用 WebSocket 实时聊天！请点击"连接服务器"按钮开始聊天。
                    </div>
                </div>

                <div class="input-area">
                    <textarea class="message-input" id="messageInput" placeholder="输入消息..." disabled></textarea>
                    <button class="send-btn" id="sendBtn" disabled>发送</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const messagesContainer = document.getElementById('messages');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const clearBtn = document.getElementById('clearBtn');
        const statusIndicator = document.getElementById('statusIndicator');
        const statusText = document.getElementById('statusText');
        const userList = document.getElementById('userList');
        const onlineCount = document.getElementById('onlineCount');
        const serverUrl = document.getElementById('serverUrl');
        const userId = document.getElementById('userId');

        let socket = null;
        let isConnected = false;
        let currentUser = null;

        // 添加消息到聊天窗口
        function addMessage(content, type, user = null, timestamp = new Date()) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;

            const timeString = timestamp.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});

            let messageHeader = '';
            let messageInfo = '';

            if (type === 'sent') {
                messageInfo = `You · ${timeString}`;
            } else if (type === 'received' && user) {
                messageHeader = `
                        <div class="message-header">
                            <div class="message-avatar" style="background-color: ${user.avatar.color}">
                                ${user.avatar.letter}
                            </div>
                            <div class="message-info">${user.name} · ${timeString}</div>
                        </div>
                    `;
            } else {
                messageInfo = '系统消息';
            }

            messageDiv.innerHTML = `
                    ${messageHeader}
                    ${messageInfo ? `<div class="message-info">${messageInfo}</div>` : ''}
                    ${content}
                `;

            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 更新用户列表
        function updateUserList(users) {
            userList.innerHTML = '';

            if (users && users.length > 0) {
                users.forEach(user => {
                    const userItem = document.createElement('li');
                    userItem.className = 'user-item';

                    userItem.innerHTML = `
                            <div class="user-avatar" style="background-color: ${user.avatar.color}">
                                ${user.avatar.letter}
                            </div>
                            <span>${user.name} ${user.id === currentUser.id ? '(You)' : ''}</span>
                        `;
                    userList.appendChild(userItem);
                });
            } else {
                const emptyItem = document.createElement('li');
                emptyItem.className = 'user-item';
                emptyItem.textContent = '暂无在线用户';
                userList.appendChild(emptyItem);
            }
        }

        // 更新在线用户数
        function updateOnlineCount(count) {
            onlineCount.textContent = count;
        }

        // 连接WebSocket服务器
        function connect() {
            if (isConnected) return;

            try {
                statusIndicator.className = 'status-indicator connecting';
                statusText.textContent = 'WebSocket 连接状态: 连接中...';

                // 创建WebSocket连接
                socket = new WebSocket('ws://localhost:8080');

                socket.onopen = function(event) {
                    console.log('WebSocket 连接已建立');
                    isConnected = true;
                    statusIndicator.className = 'status-indicator connected';
                    statusText.textContent = 'WebSocket 连接状态: 已连接';
                    messageInput.disabled = false;
                    sendBtn.disabled = false;
                    connectBtn.disabled = true;
                    disconnectBtn.disabled = false;
                    serverUrl.textContent = 'ws://localhost:8080';

                    addMessage('已成功连接到WebSocket服务器', 'system');
                };

                socket.onmessage = function(event) {
                    console.log('收到服务器消息:', event.data);
                    const data = JSON.parse(event.data);

                    switch(data.type) {
                        case 'system':
                            // 保存当前用户信息
                            if (data.currentUser) {
                                currentUser = data.currentUser;
                                userId.textContent = currentUser.id;
                            }
                            addMessage(data.message, 'system', null, new Date(data.timestamp));
                            break;

                        case 'user_join':
                            addMessage(data.message, 'system', null, new Date(data.timestamp));
                            updateOnlineCount(data.onlineCount);
                            break;

                        case 'user_leave':
                            addMessage(data.message, 'system', null, new Date(data.timestamp));
                            updateOnlineCount(data.onlineCount);
                            break;

                        case 'user_list':
                            updateUserList(data.users);
                            break;

                        case 'chat_message':
                            // 判断消息是否来自自己
                            if (currentUser && data.user.id === currentUser.id) {
                                // 这是自己发送的消息，已经在发送时显示了
                                // 这里可以选择不显示，或者显示为已发送
                            } else {
                                // 这是其他用户发送的消息
                                addMessage(data.message, 'received', data.user, new Date(data.timestamp));
                            }
                            break;
                    }
                };

                socket.onclose = function(event) {
                    console.log('WebSocket 连接已关闭');
                    isConnected = false;
                    statusIndicator.className = 'status-indicator disconnected';
                    statusText.textContent = 'WebSocket 连接状态: 已断开';
                    messageInput.disabled = true;
                    sendBtn.disabled = true;
                    connectBtn.disabled = false;
                    disconnectBtn.disabled = true;
                    serverUrl.textContent = '未连接';
                    userId.textContent = '-';
                    currentUser = null;

                    addMessage('WebSocket连接已断开', 'system');
                };

                socket.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                    statusIndicator.className = 'status-indicator disconnected';
                    statusText.textContent = 'WebSocket 连接状态: 连接失败';
                    addMessage('连接服务器失败，请检查服务器是否运行', 'system');
                };

            } catch (error) {
                console.error('连接错误:', error);
                statusIndicator.className = 'status-indicator disconnected';
                statusText.textContent = 'WebSocket 连接状态: 连接失败';
                addMessage('连接失败: ' + error.message, 'system');
            }
        }

        // 断开连接
        function disconnect() {
            if (socket) {
                socket.close();
                socket = null;
            }
            isConnected = false;
            statusIndicator.className = 'status-indicator disconnected';
            statusText.textContent = 'WebSocket 连接状态: 未连接';
            messageInput.disabled = true;
            sendBtn.disabled = true;
            connectBtn.disabled = false;
            disconnectBtn.disabled = true;
            serverUrl.textContent = '未连接';
            userId.textContent = '-';
            currentUser = null;
            updateUserList([]);
            updateOnlineCount(0);
        }

        // 发送消息
        function sendMessage() {
            if (!socket || !isConnected) {
                alert('WebSocket 未连接，无法发送消息');
                return;
            }

            const message = messageInput.value.trim();
            if (message === '') return;

            try {
                // 立即在本地显示自己发送的消息
                addMessage(message, 'sent');

                // 发送消息到服务器
                socket.send(JSON.stringify({
                    type: 'chat_message',
                    message: message
                }));

                // 清空输入框
                messageInput.value = '';

            } catch (error) {
                console.error('发送消息错误:', error);
                addMessage('发送消息失败', 'system');
            }
        }

        // 事件监听
        sendBtn.addEventListener('click', sendMessage);

        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        connectBtn.addEventListener('click', connect);

        disconnectBtn.addEventListener('click', disconnect);

        clearBtn.addEventListener('click', function() {
            messagesContainer.innerHTML = '';
            addMessage('消息历史已清空', 'system');
        });

        // 页面加载时自动连接（可选）
        // connect();
    });
</script>
</body>
</html>
